<?php


namespace App\HttpController;


use EasySwoole\Http\AbstractInterface\Controller;

use EasySwoole\Mysqli\QueryBuilder;

use EasySwoole\EasySwoole\ServerManager;
class Index extends Controller
{

    protected function p($html){
        $this->response()->write(var_export($html,true));
    }
    function index()
    {
        unlink(EASYSWOOLE_ROOT.'/result.txt');
        //https://www.cnblogs.com/jiangxiaobo/p/7987232.html
		//https://www.php.cn/php-weizijiaocheng-390580.html
		//https://www.easyswoole.com/Components/Component/csp.html
		//https://www.easyswoole.com/Components/HttpClient/introduction.html
        $url = 'https://www.dygod.net/html/gndy/dyzz/index.html';
        $client = new \EasySwoole\HttpClient\HttpClient($url);
        $html = $client->get()->getBody();

        //CP936
        //var_dump(mb_detect_encoding($html,'utf-8,gbk,gb2312'));

        $html=mb_convert_encoding($html,'utf-8','CP936');
        $html=str_replace('gb2312','utf-8',$html);
        //$this->p($html);
        $urls=[];
        \phpQuery::newDocumentHTML($html);
        $aa=pq('div.co_content8 a.ulink');
        foreach($aa as $k=>$v){
            $title=pq($v)->text();
            $url=pq($v)->attr('href');
            $urls[]=[
              'title'=>$title,
              'url'=>'https://www.dygod.net'.$url,
            ];
        }
        //并发采集内容
        go(function () use ($urls){
            $csp = new \EasySwoole\Component\Csp();
            foreach($urls as $k=>$v){
                if(!$v) continue;
                $csp->add("t_{$k}",function () use ($k,$v){
                    $client = new \EasySwoole\HttpClient\HttpClient($v['url']);
                    $html = $client->get()->getBody();
                    $html=mb_convert_encoding($html,'utf-8','CP936');
                    $html=str_replace('gb2312','utf-8',$html);
                    //file_put_contents(EASYSWOOLE_ROOT.'/html/'.$k.'.html',$html);

                    \phpQuery::newDocumentHTML($html);
                    $download_title = pq('div.title_all h1')->text();
                    $download_url = pq('a[href^="magnet:"]:eq(0)')->attr('href');
                    return [$download_title,$download_url];
                });
            }

            $result=$csp->exec(10);
            //var_dump($result);
            foreach($result as $k=>$v){
                if(!$v[1]) continue;
                file_put_contents(EASYSWOOLE_ROOT.'/result.txt',"{$v[0]}\n{$v[1]}\n",FILE_APPEND);
            }


        });
        $this->response()->write('ok');

    }

    public function collection(){
        $get = $this->request()->getQueryParams();
        $itemid=intval($get['itemid']);
        if(!$itemid){
            $this->response()->write(json_encode(['code'=>1,'msg'=>'lose itemid']));
            return;
        }
        //echo $itemid;

        $config = new \EasySwoole\Mysqli\Config([
            'host'          => '192.168.56.1',
            'port'          => 3306,
            'user'          => 'root',
            'password'      => 'root',
            'database'      => 'ashley',
            'timeout'       => 5,
            'charset'       => 'utf8mb4',
        ]);

        $db = new \EasySwoole\Mysqli\Client($config);

        $url = 'https://www.dygod.net/html/gndy/dyzz/index.html';
        $client = new \EasySwoole\HttpClient\HttpClient($url);
        $html = $client->get()->getBody();

        //CP936
        //var_dump(mb_detect_encoding($html,'utf-8,gbk,gb2312'));

        $html=mb_convert_encoding($html,'utf-8','CP936');
        $html=str_replace('gb2312','utf-8',$html);
        //$this->p($html);
        $urls=[];
        \phpQuery::newDocumentHTML($html);
        $aa=pq('div.co_content8 a.ulink');
        foreach($aa as $k=>$v){
            $title=pq($v)->text();
            $url=pq($v)->attr('href');
            $urls[]=[
                'title'=>$title,
                'url'=>'https://www.dygod.net'.$url,
            ];
        }
        //并发采集内容
        go(function () use ($urls, $itemid, $db){
            $csp = new \EasySwoole\Component\Csp();
            foreach($urls as $k=>$v){
                if(!$v) continue;
                $csp->add("t_{$k}",function () use ($k,$v){
                    $client = new \EasySwoole\HttpClient\HttpClient($v['url']);
                    $html = $client->get()->getBody();
                    $html=mb_convert_encoding($html,'utf-8','CP936');
                    $html=str_replace('gb2312','utf-8',$html);
                    //file_put_contents(EASYSWOOLE_ROOT.'/html/'.$k.'.html',$html);

                    \phpQuery::newDocumentHTML($html);
                    $download_title = pq('div.title_all h1')->text();
                    $download_url = pq('a[href^="magnet:"]:eq(0)')->attr('href');
                    return [$download_title,$download_url];
                });
            }

            $result=$csp->exec(10);
            //var_dump($result);

            $content='';
            foreach($result as $k=>$v){
                if(!$v[1]) continue;
                //file_put_contents(EASYSWOOLE_ROOT.'/result.txt',"{$v[0]}\n{$v[1]}\n",FILE_APPEND);
                $content.="{$v[0]}<br>{$v[1]}<br>";
            }

            $db->queryBuilder()->where('itemid', $itemid)->update('szh_collection', ['content' => $content, 'status'=>'yes', 'finishtime'=>time()]);
            $db->execBuilder();
            //发送通知
            $this->broadcast($itemid);
        });

        $this->response()->write(json_encode(['code'=>0,'msg'=>'success']));
    }

    protected function broadcast($itemid)
    {
        /** @var \swoole_websocket_server $server */
        $server = ServerManager::getInstance()->getSwooleServer();
        $start = 0;
        // 此处直接遍历所有FD进行消息投递
        // 生产环境请自行使用Redis记录当前在线的WebSocket客户端FD
        while (true) {
            $conn_list = $server->connection_list($start, 10);
            if (empty($conn_list)) {
                break;
            }
            $start = end($conn_list);
            foreach ($conn_list as $fd) {
                $info = $server->getClientInfo($fd);
                /** 判断此fd 是否是一个有效的 websocket 连接 */
                if ($info && $info['websocket_status'] == WEBSOCKET_STATUS_FRAME) {
                    $server->push($fd, "itemid：{$itemid} 号任务已于".date('Y-m-d H:i:s')."成功完成！");
                }
            }
        }
    }

    protected function actionNotFound(?string $action)
    {
        $this->response()->withStatus(404);
        $file = EASYSWOOLE_ROOT.'/vendor/easyswoole/easyswoole/src/Resource/Http/404.html';
        if(!is_file($file)){
            $file = EASYSWOOLE_ROOT.'/src/Resource/Http/404.html';
        }
        $this->response()->write(file_get_contents($file));
    }
}